#include "phong_shader.h"
#include "GMaterial.h"
#include "GTexture.h"
#include "GModel.h"
#include "GCamera.h"

void PhongShader::vertex_shader(VertexProp* vertex, Payload& payload)
{
	vertex->clip_pos = payload.mvp_matrix * vertex->vertex_pos;
	vertex->world_pos = payload.model_matrix * vertex->vertex_pos;
}

Eigen::Vector3f PhongShader::fragment_shader(VertexProp* vertex, Payload& payload)
{
	Vector3f amb_light_intensity(5, 5, 5);
	float p = 150.0;
	light light1{ {2, 4, 2},{50, 50, 50} };
	std::vector<light> lights = { light1 };
	
	Vector3f ka(0.0005, 0.0005, 0.0005);
	Vector3f ks(0.6937, 0.6937, 0.6937);
	Vector3f kd = payload.pModel->m_pMaterial->m_pMainTex->SampleTex(vertex->uv.x(), vertex->uv.y());
	Vector3f worldPos = vertex->world_pos.head<3>();

	Vector3f result_color = Vector3f(0, 0, 0);
	for (auto& light : lights)
	{
		Vector3f ambient, diffuse, specular;
		Vector3f normal = vertex->normal.normalized();
		Vector3f l = Vector3f(1, 3, 1).normalized();
		Vector3f v = (payload.pCamera->m_vEye - worldPos).normalized();
		Vector3f h = (l + v).normalized();
		
		float r = (light.pos - worldPos).squaredNorm();
		ambient = ka.cwiseProduct(amb_light_intensity);
		//diffuse = kd.cwiseProduct(light.intensity) * max(0, l.dot(normal)) / r;
		diffuse = kd * max(0, l.dot(normal));
		specular = ks.cwiseProduct(light.intensity) * max(0, pow(normal.dot(h), p)) / r;

		result_color += diffuse * 0.2 + kd * 0.7 + specular;
	}
	return result_color;
}